package com.jingtai.validate.validator;

import java.util.stream.Collectors;

import javax.validation.Validation;
import javax.validation.Validator;

import org.hibernate.validator.HibernateValidator;
import org.springframework.stereotype.Component;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.SmartValidator;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;

@Component
public class Jsr303Validator<T> {
	private static Validator validator;
	private static SmartValidator validatorAdapter;

	static {
		// 快速返回模式
		validator = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory()
				.getValidator();

		validatorAdapter = getValidatorAdapter(validator);
	}

	public static Validator getValidator() {
		return validator;
	}

	private static SmartValidator getValidatorAdapter(Validator validator) {
		if (validatorAdapter == null) {
			validatorAdapter = new SpringValidatorAdapter(validator);
		}
		return validatorAdapter;
	}

	public Object validator(T obj) {
		BeanPropertyBindingResult result = new BeanPropertyBindingResult(obj, "bean");
		validatorAdapter.validate(obj, result);
		if (result.hasErrors()) {
			return result.getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
		}
		return obj;
	}
}
